home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13067 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: nntp.teleport.com!usenet
  2. From: GHouck <hksys@teleport.com>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Turbo C beginner: string question? Please help!
  5. Date: 4 Apr 1996 08:17:59 GMT
  6. Organization: systems hk
  7. Message-ID: <4k00jn$bsk@nadine.teleport.com>
  8. References: <Pine.SOL.3.91.960403054553.29446A-100000@jove.acs.unt.edu>
  9. NNTP-Posting-Host: ip-pdx09-29.teleport.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 1.22 (Windows; I; 32bit)
  14.  
  15. Reynaldo Ortega <rortega@jove.acs.unt.edu> wrote:
  16. >
  17. >main()
  18. >{
  19. >  char str[80];
  20. >  printf("enter you name: ");
  21. >  gets(str);
  22. >  printf("hello %s", str);
  23. >}
  24. >QUESTION:
  25. > let's say I entered the name TARANTINO, and I wanted to compare each 
  26. >single character in the string to display a count of occurences of 
  27. >each character. How would I code this? Here is an example to clarify
  28. >what I am asking:
  29. Ray,
  30.  
  31. First off, the mantra in this newsgroup is NEVER USE gets(), since it
  32. doesn't give you protection against a string being entered which is
  33. longer than your character array; however, it does in a pinch.
  34.  
  35. I'd do something like this:
  36.  
  37.   char string[80];
  38.   int  chrCounts[356];
  39.   int  i;
  40.  
  41.   memset( chrCounts,0,sizeof(chrCounts) ); /* clear 256 counters */
  42.   ...
  43.   fgets( string,sizeof(string),stdin );    /* get your string */
  44.   ...
  45.   for( i=0; i<strlen(string); i++ )        /* seq thru chars, tallying each */
  46.     ++chrCounts[(unsigned)string[i]];
  47.   ...
  48.   for( i=0; i<256; i++ )                   /* for each non-zero count print it */
  49.     if( chrCounts[i] > 0 )                 /* i is each character as an index */
  50.       printf( "%s has %d %c's",string,chrCounts[i],i );
  51.   ...
  52.  
  53. Yours, Geoff Houck
  54.   
  55.  
  56.